import fileApi from "@/uni_modules/hbh-fileIo/js_sdk/index.js"
export function splitTxtContent(novelContent, fileName) {
	return new Promise(async (reslove, reject) => {
		let regex = /===.*?===/g;
		let titleArr = novelContent.match(regex)
		let contentList = novelContent.split(regex);
		if (titleArr != null) {
			const childResult = await fileApi
				.createMuchDirectory(["documents",
					"downloadTxt", fileName,
					"subchapter"
				])
			if (childResult.code == 200) {
				let i = 0
				while (i < titleArr.length) {
					let titleName = titleArr[i].substring(3, titleArr[i].length - 3)
					const res = await createAndWrite(fileName, titleName, contentList[i], i + 1)
					i++
				}
				const listRes = await storageListTxt(titleArr, fileName)
				console.log(listRes)
				//创建一个标记成功的目录
				const childResult2 = await fileApi
					.createMuchDirectory(["documents",
						"downloadTxt", fileName,
						"success"
					])
				console.log(childResult2)
				if (childResult2.code == 200) {
					reslove({
						code: 200,
						msg: "切割完毕！"
					})
				} else {
					reslove({
						code: 400,
						msg: "目录创失败！"
					})
				}
				// 请求本地文件系统对象

			} else {
				reslove({
					code: 400,
					msg: "目录创建失败！"
				})
			}

		} else {
			reslove({
				code: 400,
				msg: "改小说内容格式怪异！"
			})
		}
	})
}

function createAndWrite(fileName, titleName, content, i) {
	// console.log(`downloadTxt/${fileName}/subchapter/${titleName}@china${i+1}.txt`)
	return new Promise((reslove, reject) => {
		plus.io.requestFileSystem(
			plus.io
			.PUBLIC_DOCUMENTS, // 文件系统中的根目录
			fs => {
				// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
				fs.root.getFile( //创建文件名前要将系统不支持的特殊符号替换掉,是个坑
					`downloadTxt/${fileName}/subchapter/${titleName.replace(/[<>:\/?"*|]/g,'').trim()}-H-${i}.txt`, {
						create: true // 文件不存在则创建
					}, fileEntry => {
						fileEntry
							.createWriter(
								writer => {
									// 写入文件成功完成的回调函数
									writer.onwrite =
										e => {
											reslove({
												code: 200,
												msg: "写入数据成功"
											})
										};
									// 写入数据
									writer.write(
										content
									);
								}
							)
					}, e => {
						reslove({
							code: 400,
							msg: e.message
						})
					});
			},
			e => {
				reslove({
					code: 400,
					msg: e.message
				})
			}
		);
	})
}
//为了加快目录速度，此函数将目录存入一个list.txt文件
function storageListTxt(arr, fileName) {
	return new Promise(async (reslove, reject) => {
		const childResult = await fileApi
			.createMuchDirectory(["documents",
				"downloadTxt", fileName,
				"list"
			])
		if (childResult.code == 200) {
			arr = arr.map(item => {
				item = item.substring(3, item.length - 3)
				return item
			})
			//再次优化目录,每100章分割一次，滚动加载吧
			let index = 0
			while (index < arr.length) {
				let chunk = arr.slice(index, index + 200).join("-H-");
				// 这里可以对切割出来的 chunk 进行操作，比如打印出来
				const res = await storageSmallList(chunk, fileName, (index + 200)>arr.length?arr.length:index + 200)
				index += 200;
			}
			reslove({
				code: 200,
				msg: "切割目录完成！"
			})
		} else {
			reslove({
				code: 400,
				msg: "切割目录失败！"
			})
		}
	})
}
//存储小段目录
function storageSmallList(str, fileName, index) {
	return new Promise((reslove, reject) => {
		plus.io.requestFileSystem(
			plus.io
			.PUBLIC_DOCUMENTS, // 文件系统中的根目录
			fs => {
				// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
				fs.root.getFile( //创建文件名前要将系统不支持的特殊符号替换掉,是个坑
					`downloadTxt/${fileName}/list/${index}.txt`, {
						create: true // 文件不存在则创建
					}, fileEntry => {
						fileEntry
							.createWriter(
								writer => {
									// 写入文件成功完成的回调函数
									writer.onwrite =
										e => {
											reslove({
												code: 200,
												msg: "写入数据成功"
											})
										};
									// 写入数据
									writer.write(
										str
									);
								}
							)
					}, e => {
						reslove({
							code: 400,
							msg: e.message
						})
					});
			},
			e => {
				reslove({
					code: 400,
					msg: e.message
				})
			}
		);
	})
}